package base.core.security.dms;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @Description 鉴权拦截器
 * @Author Pengwei
 * @CreatDate 2022/1/10 23:42
 */
public class DmsJwtAuthorizationFilter extends BasicAuthenticationFilter {

    public DmsJwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        DmsTokenInfo tokenInfo = DmsJwtUtils.getTokenInfo(request);

        //无token或者获取token失败或者Userid为空
        if (tokenInfo == null || StringUtils.isBlank(tokenInfo.getUserId())) {
            chain.doFilter(request, response);
            return;
        }

        //设置Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(tokenInfo, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        super.doFilterInternal(request, response, chain);
    }
}
